from celery import Celery
from config import Config

def create_celery_app(app=None):
    """创建 Celery 应用实例"""
    celery = Celery(
        'auto-fastlane',
        broker_url=Config.CELERY_BROKER_URL,
        result_backend=Config.CELERY_RESULT_BACKEND,
        include=['tasks.version_tasks']
    )
    
    # 配置 Celery
    class CeleryConfig:
        broker_url = Config.CELERY_BROKER_URL
        result_backend = Config.CELERY_RESULT_BACKEND
        task_serializer = 'json'
        accept_content = ['json']
        result_serializer = 'json'
        timezone = 'Asia/Shanghai'
        enable_utc = True
        task_track_started = True
        broker_transport_options = {
            'visibility_timeout': 3600,
            'socket_timeout': 30,
            'socket_connect_timeout': 30,
        }
        broker_connection_retry = True
        broker_connection_retry_on_startup = True
        broker_connection_max_retries = 10
        redis_max_connections = 10
        worker_prefetch_multiplier = 1
        worker_concurrency = 1
    
    celery.config_from_object(CeleryConfig)
    
    if app:
        # 将 Flask 应用上下文推送到 Celery 任务中
        TaskBase = celery.Task
        class ContextTask(TaskBase):
            abstract = True
            def __call__(self, *args, **kwargs):
                with app.app_context():
                    return TaskBase.__call__(self, *args, **kwargs)
        celery.Task = ContextTask
    
    return celery

# 创建 Celery 实例
celery_app = create_celery_app()
